/*
 *  Disc Catalog
 *  A little application to quickly catalog and find contents of your
 *  DVD archives.
 *
 *  SearchManager.h
 *  The class that manages the document's search capabilities.
 *
 *  Created by Nicola Gigante on 31/12/08.
 *  Copyright (C) 2008  Nicola Gigante
 *
 *  This program is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation, either version 3 of the License, or
 *  (at your option) any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

#import "SearchManager.h"

@implementation SearchManager

@synthesize keyword;

- (File *)filter:(File *)file
{
	if([file isFile])
		return [self fileMatch:file] ? file : nil;
	
	File *newFile = [[File alloc] initWithFile:file andChildren:NO];
	for(File *f in file.files)
	{
		File *filtered = [self filter:f];
		if(filtered)
			[newFile insertObject:filtered inFilesAtIndex:[newFile countOfFiles]];
	}
	return [newFile countOfFiles] ? newFile : nil;
}

- (BOOL) fileMatch:(File *)file
{
	return [file.name rangeOfString:self.keyword options:NSCaseInsensitiveSearch].location != NSNotFound ||
		   [file.notes rangeOfString:self.keyword options:NSCaseInsensitiveSearch].location != NSNotFound;	
}

- (NSArray *)filterDiscs: (NSArray *)discs
{
	NSMutableArray *array = [NSMutableArray array];
	for(Disc *disc in discs)
	{
		File *filtered = [self filter: disc];
		if(filtered)
		{
			Disc *newDisc = [[Disc alloc] initWithDirectory:filtered];
			newDisc.label = disc.label;
			newDisc.isExplicit = disc.isExplicit;
			[array insertObject:newDisc atIndex:[array count]];
		}
	}
	
	return array;
}

@end
